package com.pi.shisan.util.spipoint;

import com.pi.shisan.AsCloseable;
import com.pi.shisan.util.Pi8x8Util;

import java.io.IOException;

/**
 * 往物理硬件上发送数据的SpiPoint
 */
public class MultipleFlushSpi implements MultipleXyToSpiConverter, DataWriter, AsCloseable {

    protected MultipleXyToSpiConverter multipleXyToSpiConverter;

    public MultipleFlushSpi(MultipleXyToSpiConverter multipleXyToSpiConverter) {
        this.multipleXyToSpiConverter = multipleXyToSpiConverter;
    }

    public void init() {
        Pi8x8Util.open(multipleXyToSpiConverter.getW() * multipleXyToSpiConverter.getH());
    }

    @Override
    public long[] toSpiPoints() {
        return multipleXyToSpiConverter.toSpiPoints();
    }

    @Override
    public void add(int x, int y) {
        multipleXyToSpiConverter.add(x, y);
    }

    @Override
    public void put(int x, int y) {
        multipleXyToSpiConverter.put(x, y);
    }

    @Override
    public void put(int xy) {
        multipleXyToSpiConverter.put(xy);
    }

    @Override
    public void remove(int x, int y) {
        multipleXyToSpiConverter.remove(x, y);
    }

    @Override
    public void delete(int x, int y) {
        multipleXyToSpiConverter.delete(x, y);
    }

    @Override
    public void delete(int xy) {
        multipleXyToSpiConverter.delete(xy);
    }

    @Override
    public void clear() {
        multipleXyToSpiConverter.clear();
    }

    @Override
    public void flushData() {
        Pi8x8Util.writeData(toSpiPoints());
    }

    @Override
    public void lightLevel(int level) {
        Pi8x8Util.setupLighter(level, multipleXyToSpiConverter.getW() * multipleXyToSpiConverter.getH());
    }

    @Override
    public int getW() {
        return multipleXyToSpiConverter.getW();
    }

    @Override
    public int getH() {
        return multipleXyToSpiConverter.getH();
    }

    @Override
    public String toString() {
        return multipleXyToSpiConverter.toString();
    }

    /**
     * 这个关闭务必要在绘制的单线程中执行
     * @throws IOException
     */
    @Override
    public void close(){
        multipleXyToSpiConverter.clear();
        flushData();
        Pi8x8Util.close(multipleXyToSpiConverter.getW() * multipleXyToSpiConverter.getH());
    }
}
